﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ExamSharedClasses.Commands;
using ExamSharedClasses;


namespace ExamClient {
    /// <summary>
    /// (k) Der ExamFrame enthält selbst einen Dockpanel, an den die einzelnen
    /// Fragen als Frage angeheftet werden können. Er enthält zusätzlich eine
    /// Variable, die eine laufende Klausur darstellt und auch eine, die die
    /// restliche Zeit angibt.
    /// </summary>
    public partial class ExamPage : Page {
        
        public ViewExam Cve { get; set; }

        public int DurationCountDown { get; set; }
        public bool IsExamRunning { get; set; }

        public ExamStartPage ExamMainFrame { get; set; }
        public List<Page> QuestionCatalogue { get; set; }

        public ExamPage( ViewExam comViewExam ) {
            InitializeComponent();
            
            App.DispatcherTimer.Tick += new EventHandler( ExamTimerMethod ); // Timermethode mit den anderen (UpdateGUI) sekündlich aufrufen
            App.ExamPage = this;
            this.Cve = comViewExam;

            ExamMainFrame = new ExamStartPage(); // Hauptseite

            QuestionCatalogue = new List<Page>();
            string message = "";

            int i = 0;
            // aus Klausurvorlage eine Klausur machen
            this.Cve.Exam = new ExamUser( App.UserAddress, new DateTime(), new DateTime(), new DateTime(), ( ExamWithQuestions )Cve.Exam ); // "Ausfüllen von Namen"
            ExamUser eu = ( ExamUser )this.Cve.Exam; i = 0;
            examFrame.Content = ExamMainFrame; // Hauptseite aufrufen?

            ExamWithQuestions eq = (ExamWithQuestions)this.Cve.Exam;
            // Den "Fragenkatalog füllen
            int iMax = eq.AnswerList.Count;
            for (i = 0; i < iMax; i++) {

                if (eq.AnswerList[i] is AnswerTypeMultiple) {
                    AnswerTypeMultiple atm = ( AnswerTypeMultiple )eq.AnswerList[i];
                    QuestionCatalogue.Add(new QuestionTypeMultiplePage( atm ));
                } else if (eq.AnswerList[i].AnswerQuestion is QuestionTypeSingleMultiple) {
                    AnswerTypeSingleMultiple atsm = ( AnswerTypeSingleMultiple )eq.AnswerList[i];
                    QuestionCatalogue.Add(new QuestionTypeSingleMultiplePage( atsm ));
                } else if (eq.AnswerList[i].AnswerQuestion is QuestionTypeText) {
                    AnswerTypeText att = ( AnswerTypeText )eq.AnswerList[i];
                    QuestionCatalogue.Add(new QuestionTypeTextPage( att ));
                }

            }
            DurationCountDown = eu.ExamDuration;
            examNameLabel.Content = eu.ExamName;
            // ProgressBar für verbleibende Fragen initialisieren
            progressBarQuestions.Maximum = iMax;
            progressBarQuestions.Minimum = 0;
            progressBarQuestions.Value = 0;
            progressBarQuestionsText.Text = "Anzahl Fragen: " + eq.AnswerList.Count; ;
            // ProgressBar für verbleibende Fragen initialisieren
            progressBarTime.Maximum = eq.ExamDuration;
            progressBarTime.Minimum = 0;
            progressBarTime.Value = eq.ExamDuration;
            progressBarTimeText.Text = "Dauer: " + Tools.GetReadableTimeStringOfValueWithSeconds(eq.ExamDuration);

            


            i = 0;

            if ( !message.Equals( "" ) )
                new HintWindow( message );

            UpdateFrame();
        }

        //App.DispatcherTimer.Tick -= new EventHandler( ExamTimerMethod ); //<------------------

        public void ExamTimerMethod( object sender, EventArgs e ) {
            if ( IsExamRunning ) {

                DurationCountDown--;

                if ( DurationCountDown <= 0 ) {
                    ExamMainFrame.sendButton_Click( null, null );
                }
                Tools.SerializeObjectToFile(Cve, "klausur.tmp");
            }
            UpdateFrame();
        }

        public int GetAnsweredQuestions() {
            int i = 0;
            ExamWithQuestions ewq = (ExamWithQuestions)Cve.Exam;
            foreach (Answer a in ewq.AnswerList)
	        {
                i += ewq.AnswerList[i].HasSetAnswer() ? 1 : 0;
	        }
            Console.WriteLine("GetUnAnsweredQuestionsLeft() == "+i);
            return i;
        }
        public double GetUnAnsweredQuestionsLeftAsDouble() {
            double a = 0, b = 0;
            ExamWithQuestions ewq = ( ExamWithQuestions )Cve.Exam;
            foreach ( Answer answer in ewq.AnswerList ) {
                a += answer.HasSetAnswer() ? 1 : 0;
                b += 1;
            }
            return a / b;
        }
        public double GetTimeLeftAsDouble() {
            double a = DurationCountDown, b = Cve.Exam.ExamDuration;
            return a / b;
        }        

        public void UpdateFrame() {

            int sum = 0, i = 0;
            ExamWithQuestions eq = (ExamWithQuestions)Cve.Exam;

            if (Cve.Exam is ExamUser) {
                ExamUser eu = (ExamUser)Cve.Exam;
                questionListBox.Items.Clear();
                
                foreach (int points in eu.PointsList) {
                    string text =   (eu.AnswerList[i].HasSetAnswer()? "[beantwortet] " : "") + 
                                    ("Frage Nr. " + (i+1) + " " + eu.AnswerList[i].AnswerQuestion.ToShortInfoString()) + 
                                    ((i == QuestionCatalogue.IndexOf( ( Page )examFrame.Content ) ) ? " <---" : "");
                    questionListBox.Items.Add(text);
                    sum += points;
                    ++i;
                }

            }

            // ProgressBarTime value verringern
            progressBarTime.Value = DurationCountDown;
            // ProgressbarQuestions auf beantwortete fragen setzen
            progressBarQuestions.Value = GetAnsweredQuestions();
            if ( IsExamRunning ) {
                progressBarQuestionsText.Text = "Beantwortete Fragen: " + GetAnsweredQuestions() +" / " + eq.AnswerList.Count;
                progressBarQuestions.Foreground = new SolidColorBrush(System.Windows.Media.Color.FromRgb((byte)((1 - GetUnAnsweredQuestionsLeftAsDouble()) * 255), (byte)((GetUnAnsweredQuestionsLeftAsDouble()) * 255), 0));
                progressBarTimeText.Text = "Restzeit: " + Tools.GetReadableTimeStringOfValueWithSeconds(DurationCountDown);
                progressBarTime.Foreground = new SolidColorBrush(System.Windows.Media.Color.FromRgb((byte)((1 - GetTimeLeftAsDouble()) * 255), (byte)((GetTimeLeftAsDouble()) * 255), 0));
            } else {
                progressBarQuestionsText.Text = "Anzahl Fragen: " + eq.AnswerList.Count; ;
                progressBarTimeText.Text = "Dauer: " + Tools.GetReadableTimeStringOfValueWithSeconds(eq.ExamDuration);
            }
            
        }

        /// <summary>
        /// Aus der List der Fragen-Pages wird versucht, das nächste
        /// Element aufzurufen. Sollte die letzte Frage erreicht worden
        /// sein, wird von ihr auf die Hauptseite gewechselt.
        /// </summary>
        public void BindNextPageToFrame() {
            int index = -1;
            try {
                index = QuestionCatalogue.IndexOf( (Page)examFrame.Content );
                if ( ( index + 1 ) >= QuestionCatalogue.Count ) {
                    examFrame.Content = ExamMainFrame;
                } else {
                    examFrame.Content = QuestionCatalogue[index + 1];
                }
            } catch ( Exception ex ) {
                App.Display( ex );
            }
        }

        private void questionListBox_MouseDoubleClick( object sender, MouseButtonEventArgs e ) {

            if (IsExamRunning) {
                int index = 0;
                try {
                    ExamWithQuestions eq = (ExamWithQuestions)this.Cve.Exam;
                    index = questionListBox.SelectedIndex;
                    examFrame.Content = QuestionCatalogue[index];
                } catch (Exception) {
                    throw;
                }
            }
            
        }

        public void FillProgressBarQuestions()
        {

        }

    }
}
